package com.ruantu.clothing.util.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruantu.clothing.controller.RukuController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class WeixinUtil {
    private static final Logger logger = LoggerFactory.getLogger(RukuController.class);
    private static String  tokenQ=null;
    private static long gtTokenTime; //上次获取Token时间
    // static String jsapi_ticket=getTicket(getAccessToken());


    public static Map<String, String> sign( String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        String jsapi_ticket=getTicket();
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        //System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appId",WXParameter.getAppId());
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    /**
     * access_token是公众号的全局唯一接口调用凭据
     * */
    public static String getAccessToken(){
        Date dt= new Date();
        gtTokenTime=(dt.getTime()/1000);
        //System.out.println("当前Token获取时间："+gtTokenTime);
        String accessToken = "";
        String grantType = "client_credential";// 获取access_token填写client_credential
        String appId = WXParameter.getAppId();// 第三方用户唯一凭证
        String secret = WXParameter.getSecret();// 第三方用户唯一凭证密钥，即appsecret
        // 这个url链接地址和参数皆不能变
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grantType+"&appid="+appId+"&secret="+secret;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            logger.info("获取access_token返回的message:"+message);
            JSONObject demoJson = JSON.parseObject(message);
            logger.info("获取access_token返回的json:"+demoJson);
            accessToken = demoJson.getString("access_token");
            logger.info("新获取的access_token:"+accessToken);
            is.close();
        }catch (Exception e){
            logger.error("获取access_token发生异常");
        }
        return accessToken;
    }

    /**
     * sapi_ticket是公众号用于调用微信JS接口的临时票据,获得jsapi_ticket之后，就可以生成JSSDK权限验证的签名了
     * 参与签名的字段包括noncestr（随机字符串）, 有效的jsapi_ticket, timestamp（时间戳）, url（当前网页的URL，不包含#及其后面部分）
     * @param
     * @return
     */
    public static String getTicket() {
        Date dt= new Date();
        long gtReqTime=(dt.getTime()/1000);//当前请求时间
        long shiCha=(gtReqTime-gtTokenTime);
        //System.out.println("时差："+shiCha);
        if (shiCha>=7000||tokenQ==null){
            tokenQ=getAccessToken();//当前token
        }
        //System.out.println("当前token:"+tokenQ);
        String ticket = null;
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + tokenQ + "&type=jsapi";// 这个url链接和参数不能变
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSON.parseObject(message);
            ticket = demoJson.getString("ticket");
            is.close();
        } catch (Exception e) {
            logger.error("获取ticket发生错误");
        }
        return ticket;
    }

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            logger.error("SHA1发生错误");
        }
        return "";
    }


    /* public static void main(String[] args) {
        //String jsapi_ticket = getTicket(getAccessToken());

        // 注意 URL 一定要动态获取，不能 hardcode
        String url = "http://example.com";
        Map<String, String> ret = sign(url);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    };*/

//时间测试
  /* public static void main(String[] args) {
        Date dt= new Date();
        gtTokenTime= (dt.getTime()/1000);//这就是距离1970年1月1日0点0分0秒的秒数
       gtReqTime= dt.getTime()/1000;
       System.out.println(gtTokenTime+"---"+gtReqTime);
       long shiCha=(gtReqTime-gtTokenTime);
        System.out.println(shiCha);//与上面的相同

    }*/

  /* public static void main(String[] args) {

       System.out.println(getTicket());
   }*/
}
